package cn.bone.base.jms3;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * Created by MD-01 on 2016/9/12.
 */
public class TopicReceiver {

    private static final String BROCK_URL = "tcp://localhost:61616";
    private static final String TARGET = "cn.bone.topic";

    public static void run() throws Exception{
    TopicConnection conn = null;
    TopicSession session = null;

    //创建连接工厂
    TopicConnectionFactory factory = new ActiveMQConnectionFactory(
            ActiveMQConnection.DEFAULT_USER,
            ActiveMQConnection.DEFAULT_PASSWORD,
            BROCK_URL);
    //通过工厂创建一个连接
    conn = factory.createTopicConnection();
    //启动连接
  conn.start();
    //创建一个session会话
    session = conn.createTopicSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
    //创建一个消息队列
    Topic topic = session.createTopic(TARGET);
    //创建消息消费者
    TopicSubscriber subscriber = session.createSubscriber(topic);

  subscriber.setMessageListener(new MessageListener() {

        public void onMessage(Message message) {
            if(message!=null){
                MapMessage map = (MapMessage)message;
                try {
                    System.out.println(map.getLong("time")+"接收#"+map.getString("text"));
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        }
    });
  Thread.sleep(1000*100);

  session.commit();
  session.close();
  conn.close();
}

    public static void main(String[] args) {

        try {
            run();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
